import { message } from 'antd';
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';

import datasetService from '@/api/services/datasetService';
import orgService from '@/api/services/orgService';
import {
  DatasetListItem,
  DatasetListReq,
  CollectionListReq,
  UploadFileCollection,
  KnowledgeListRes,
  KnowledgeListReq,
  RolesListRes,
  GetDatasetReq,
} from '@/common/types';
import { StorageEnum } from '@/types/enum';

type AddedDatasetFiles = {
  datasetId: string;
  files: UploadFileCollection[];
};

type State = {
  allDatasets: DatasetListItem[];
  flowAllDatasets: DatasetListItem[];
  allDatasetsTotal: number;
  myDatasets: DatasetListItem[];
  addedDatasetFiles: AddedDatasetFiles[];
  expandedKeys: string[];
  parentIdstore: string;
  approvalCount: number;
  rolesList: RolesListRes[];
  datasetStatus: string;
  ungroupedId: string;
};

type Action = {
  getDatasetStatus: (status: string) => void;
  getParentId: (id: string) => void;
  getRolesList: (appId: string) => Array<RolesListRes>;
  loadAllDatasets: (req: KnowledgeListRes) => void;
  getAllDatasets: (req: DatasetListReq) => void;
  loadAllDatasets1: (req: KnowledgeListRes) => void;
  loadMyDatasets: (req: DatasetListReq) => void;
  loadCollections: (req: CollectionListReq) => void;
  addAddedDatasetFiles: (datasetId: string, file: UploadFileCollection) => void;
  clearAddedDatasetFiles: () => void;
  removeAddedDatasetFile: (datasetId: string, file: UploadFileCollection) => void;
  setAddedDatasetFiles: (datasetId: string, files: UploadFileCollection[]) => void;
  updateAddedDatasetFile: (datasetId: string, file: UploadFileCollection) => void;
  resetAddedDatasetFiles: (datasetId: string) => void;
  getAddedDatasetFiles: (datasetId: string) => UploadFileCollection[];
  setExpandedKeys: (keys: string[]) => void;
  updateExpandedKeys: (keys: string[]) => void;
  getApprovalList: (req: KnowledgeListReq) => void;
  getUngroupedId: (id: string) => void;
};

export const useDatasetStore = create<State & Action>()(
  persist(
    immer((set, get) => ({
      allDatasets: [],
      flowAllDatasets: [],
      myDatasets: [],
      addedDatasetFiles: [],
      expandedKeys: [],
      allDatasetsTotal: 0,
      parentIdstore: '',
      approvalCount: 0,
      rolesList: [],
      datasetStatus: '',
      ungroupedId: '',
      getUngroupedId: (id: string) => {
        set((state) => {
          state.ungroupedId = id;
        });
      },
      getDatasetStatus: (status: string) => {
        set((state) => {
          state.datasetStatus = status;
        });
      },
      getParentId: (id: string) => {
        set((state) => {
          state.parentIdstore = id;
        });
      },
      getRolesList: async (appId: string) => {
        const response = await orgService.getRole(appId);
        set((state) => {
          state.rolesList = response;
        });
        return response;
      },
      // loadAllDatasets: async (req: KnowledgeListRes) => {
      //   // const response = await datasetService.datasetList(req);
      //   const response = await datasetService.getDatasetList(req);
      //   const data = response.list;
      //   console.log(response);
      //   set((state) => {
      //     state.allDatasets = data;
      //     state.allDatasetsTotal = response.total;
      //   });
      //   return data;
      // },
      loadAllDatasets: async (req: GetDatasetReq) => {
        // const response = await datasetService.datasetList(req);
        const response = await orgService.getDataset({ appId: req?.app_id });
        const data = response.list;
        set((state) => {
          state.allDatasets = data;
          state.allDatasetsTotal = response.total;
        });
        return data;
      },
      getAllDatasets: async (req: DatasetListReq) => {
        const response = await datasetService.allDatasetList(req);
        const data = response;
        set((state) => {
          state.flowAllDatasets = data;
        });
        return data;
      },
      loadAllDatasets1: async (req: KnowledgeListRes) => {
        // const response = await datasetService.datasetList(req);
        const response = await datasetService.getDatasetList(req);
        const data = response;
        return data;
      },
      getApprovalList: async (req: KnowledgeListReq) => {
        const response = await datasetService.knowledgeBaseApprovalList(req);
        const data = response.total;
        set((state) => {
          state.approvalCount = data;
        });
      },
      loadMyDatasets: async () => {
        const response = await fetch('/api/datasets/my');
        const data = await response.json();
        set((state) => {
          state.myDatasets = data;
        });
        return data;
      },
      loadCollections: async (req: CollectionListReq) => {
        if (req?.searchText && /[\\/*?+"~()[\]{}|^]/.test(req?.searchText)) {
          message.error('搜索内容包含非法字符，请重新输入');
          return {
            total: 0,
            data: [],
          };
        }
        const response = await datasetService.collectionList(req);
        const data = await response;
        return data;
      },
      addAddedDatasetFiles: async (datasetId: string, file: UploadFileCollection) => {
        set((state) => {
          const files = state.addedDatasetFiles.find((item) => item.datasetId === datasetId);
          if (files) {
            if (file?.type == 'url') {
              const existingIndex = files.files.findIndex((item) => item.uid === file?.uid);
              if (existingIndex !== -1) {
                files.files.splice(existingIndex, 1);
              }
              files.files.push(file);
            } else {
              files.files.push(file);
            }
          } else {
            const files = [file];
            state.addedDatasetFiles.push({ datasetId, files });
          }
        });
      },
      clearAddedDatasetFiles: () => {
        set((state) => {
          state.addedDatasetFiles = [];
        });
      },
      removeAddedDatasetFile: (datasetId: string, file: UploadFileCollection) => {
        set((state) => {
          const files = state.addedDatasetFiles.find((item) => item.datasetId === datasetId);
          if (files) {
            const index = files.files.findIndex((item) => item.uid === file.uid);
            if (index !== -1) {
              files.files.splice(index, 1);
            }
          }
        });
      },
      updateAddedDatasetFile: (datasetId: string, file: UploadFileCollection) => {
        set((state) => {
          const dataset = state.addedDatasetFiles.find((item) => item.datasetId === datasetId);
          if (dataset) {
            console.log(file, '----file');
            const currentFile = dataset.files.find((item) => item.uid === file.uid);
            if (currentFile) {
              // if (file.fileId !== undefined && file.fileId!== "") {
              //   currentFile.fileId = file.fileId;
              // }
              if (file.fileId?.fileId !== undefined && file.fileId?.fileId !== '') {
                currentFile.fileId = file.fileId?.fileId;
              }
              if (file.percent !== undefined) {
                currentFile.percent = file.percent;
              }
              if (file.isDelete !== undefined) {
                currentFile.isDelete = file.isDelete;
              }
              if (file.size !== undefined) {
                currentFile.size = file.size;
              }
              if (file.datasetId !== undefined) {
                currentFile.datasetId = file.datasetId;
              }
              if (file.type !== undefined) {
                currentFile.type = file.type;
              }
              if (file.name !== undefined) {
                currentFile.name = file.name;
              }
              if (file.status !== undefined) {
                currentFile.status = file.status;
              }
              if (file.statusCn !== undefined) {
                currentFile.statusCn = file.statusCn;
              }
              if (file.pageCount !== undefined) {
                // 处理 pageCount 属性
                currentFile.pageCount = file.pageCount;
              }
            }
          }
        });
      },
      setAddedDatasetFiles: (datasetId: string, files: UploadFileCollection[]) => {
        set((state) => {
          console.log(datasetId, files);

          if (state.addedDatasetFiles.some((item) => item.datasetId === datasetId)) {
            state.addedDatasetFiles = state.addedDatasetFiles.map((item) => {
              if (item.datasetId === datasetId) {
                item.files = files;
              }
              return item;
            });
          } else {
            state.addedDatasetFiles.push({ datasetId, files });
          }
        });
      },
      resetAddedDatasetFiles: (datasetId: string) => {
        set((state) => {
          state.addedDatasetFiles = state.addedDatasetFiles.filter(
            (item) => item.datasetId !== datasetId,
          );
        });
      },
      getAddedDatasetFiles: (datasetId: string) => {
        const addedDatasetFiles = get().addedDatasetFiles.find(
          (item) => item.datasetId === datasetId,
        );
        if (addedDatasetFiles?.files) {
          const filesCopy = [...addedDatasetFiles.files];
          const sortedFiles = filesCopy.sort((a, b) => (b?.percent || 0) - (a?.percent || 0));
          return sortedFiles;
        }
        return [];

        // return addedDatasetFiles?.files || [];
      },
      setExpandedKeys: (expandedKeys: string[]) => {
        set((state) => {
          const keys = new Set(expandedKeys);
          state.expandedKeys = [...keys];
        });
      },
      updateExpandedKeys: (keys: string[]) => {
        set((state) => {
          const eks = state.expandedKeys ? new Set(state.expandedKeys) : undefined;
          console.log(eks, keys);
          if (eks) {
            eks.forEach((item) => {
              if (keys.every((key) => key !== item)) {
                eks.delete(item);
              }
            });
            state.expandedKeys = [...eks];
          } else {
            state.expandedKeys = [];
          }
        });
      },
    })),
    {
      name: StorageEnum.DatasetStorage,
      version: 1,
      partialize: (state) => ({}),
    },
  ),
);
